Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

361
Views
¿Cómo resolver JsonWebTokenError "firma no válida" después de asignar algunas informaciones al token generado?

Tengo un problema al intentar verificar el token (funcionaba bien antes de agregarle algunos datos antes de generarlo)... ¡pero ahora parece que no funciona!

Así es como genero el token cuando el usuario envía una solicitud POST (inicio de sesión)

 require('dotenv') const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs') const Role = require('../models/Role'); const Section = require('../models/Section'); const User = require('../models/User'); // Login ! router.post('/', async (req, res) => { let sections_fetched = []; // Validate data // Check username const user = await User.findOne({username: req.body.username }); if(!user) return res.status(400).send('Wrong user login credentials !'); // Check password const is_pass_valid = await bcrypt.compare(req.body.password , user.password); if (!is_pass_valid) return res.status(400).send('Wrong user login credentials !'); // Get role Object: const _role = await Role.findOne({_id:user.role , is_deleted:false}); if (!_role) res.json("Failed fetching role !"); // loop through sections for (let index = 0; index < _role.sections.length; index++) { const tmpRole = await Section.find({_id: _role.sections[index], is_deleted:false}); sections_fetched.push({access:tmpRole[0].access , name:tmpRole[0].name}); } // create jwt token const token = jwt.sign({username:user.username, role:{name:_role.name, sections:sections_fetched}}, 'secret', {expiresIn : '24h'}, process.env.JWT_TOKEN_SECRET); res.json({token:token}); });

este es mi medio de verificación JWT:

 require('dotenv') const jwt = require('jsonwebtoken'); module.exports = function (req, res, next) { const token = req.header('auth-token'); if (!token) return res.status(401).send('Access Denied !'); console.log(process.env.JWT_TOKEN_SECRET); console.log(token); try { const verified = jwt.verify(token, process.env.JWT_TOKEN_SECRET); req.user = verified; next(); } catch (error) { res.status(400).send('Invalid token !'); } }

y este es un ejemplo simple de lista de usuarios (¡usando el middleware de verificación JWT!):

 const verifyToken = require('../middlewares/verifyToken'); // my jwt middleware to verify ! // Listing All users router.get('/', verifyToken, async (req, res) => { try { const users = await User.find({is_deleted:false}); res.json(users); } catch (error) { console.log("err ->\n"+error); res.json({message: error}); } });
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

¿Qué es 'secreto en la línea de abajo? parece que está agregando una clave secreta dos veces, reemplace la palabra codificada 'secreto' con el token de env

 const token = jwt.sign({username:user.username, role:{name:_role.name, sections:sections_fetched}}, 'secret', {expiresIn : '24h'}, process.env.JWT_TOKEN_SECRET);
over 4 years ago · Santiago Trujillo Report

0

envíe un token de portador y su middleware debería ser así

 require('dotenv') const jwt = require('jsonwebtoken'); module.exports = (req, res, next) => { try { const token = req.headers.authorization.split(' ')[1]; // Authorization: 'Bearer TOKEN' if (!token) { throw new Error('Authentication failed!'); } const verified = jwt.verify(token, process.env.JWT_TOKEN_SECRET); req.user = verified; next(); } catch (err) { res.status(400).send('Invalid token !'); } };

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!